import { createTRPCProxyClient, loggerLink, TRPCClientError } from "@trpc/client";
import { callProcedure } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import { cookies } from "next/headers";

import { appRouter, type AppRouter } from "~/server/api/root";
import { createTRPCContext } from "~/server/api/trpc";
import { transformer } from "./shared";

export const api = createTRPCProxyClient<AppRouter>({
  transformer,
  links: [
    loggerLink({
      enabled: (op) =>
        process.env.NODE_ENV === "development" ||
        (op.direction === "down" && op.result instanceof Error),
    }),
    /**
     * Custom RSC link
     */
    () =>
      ({ op }) =>
        observable((observer) => {
          (async () => {
            try {
              const ctx = await createTRPCContext({
                headers: new Headers({
                  cookie: (await cookies()).toString(),
                  "x-trpc-source": "rsc",
                }),
              });

              const data = await callProcedure({
                procedures: appRouter._def.procedures,
                path: op.path,
                rawInput: op.input,
                ctx,
                type: op.type,
              });

              observer.next({ result: { data } });
              observer.complete();
            } catch (cause: unknown) {
              // 如果已经是 TRPCClientError，直接传递
              if (cause instanceof TRPCClientError) {
                observer.error(cause);
              } else {
                // 将其他类型的错误转换为 TRPCClientError
                observer.error(TRPCClientError.from(cause as Error));
              }
            }
          })();
        }),
  ],
});
